module ModuleInitialize
    
    use Globals
    use Toolbox

contains

    subroutine StartVals
    
    implicit none
    
    real(8) :: da, dh               ! auxiliary variables to create asset and hours grids
    integer :: ia, ix, is, ih       ! counter
    
    !!!!!!!!!!!!!!!!!!!    
    !!!     Grids   !!!
    !!!!!!!!!!!!!!!!!!!
    
    !! grid for assets !!    
    a_vec = LINSPACE_FET(0.0D0,1.0D0,Na)
    a_vec = a_vec**(1.0D0/aprm)
    a_vec = amin + (amax-amin)*a_vec

    ! Idiosyncratic shock process
    open(10,  file = 'Input/x_vec.txt',      status = 'unknown')
    read(10, *) x_vec
    close(10)
    
    open(11,  file = 'Input/Px.txt',      status = 'unknown')
    read(11, *) Px
    close(11)
    
    
    !! grid for state S !!
    is = 0
    do ix = 1, Nx
    do ia = 1, Na    
        is = is + 1
        S(is,:)  = [a_vec(ia), x_vec(ix)]
        xind(is) = ix
        aind(is) = ia
    end do
    end do
    
    
    ! grid for hours
    dh = (hmax-hmin)/dble(Nh-1)
    h_vec = [(hmin + dh*dble(ih-1), ih = 1, Nh)]

    ! Store grids
    open(1,  file = 'Output/a_vec.txt',  status = 'unknown')
    open(2,  file = 'Output/x_vec.txt',  status = 'unknown')
    open(3,  file = 'Output/S.txt',      status = 'unknown')
    open(4,  file = 'Output/params.txt',   status = 'unknown')
    open(5,  file = 'Output/h_vec.txt',  status = 'unknown')
    write(1, *) a_vec
    write(2, *) x_vec
    write(3, *) S
    write(4, *) [Na, Nx]
    write(5, *) h_vec
    close(1)
    close(2)
    close(3)
    close(4)
    close(5)
    
    end subroutine StartVals
        
end module ModuleInitialize
